import logging
import os
from dotenv import load_dotenv
from typing import List
from langchain_openai import ChatOpenAI
from langchain.prompts import ChatPromptTemplate

load_dotenv()

GPTModel = "gpt-4-0613"

base_url = os.getenv('GPT_BASE_URL')
api_key = os.getenv('GPT_API_KEY')

chat = ChatOpenAI(temperature=0.0, model=GPTModel, base_url=base_url, api_key=api_key)

template_string = """作为一个项目经理，请针对以下聊天记录进行信息总结：
    1. 找到需要总结的内容，被尖括号<>分割的内容即是需总结的内容
    2. 找出不同的话题，
    3. 针对每个话题，总结出该话题的进展、话题的阻塞问题点和下一步计划。
    
    请使用以下格式进行总结：
    话题: <话题名>
    进展: <该话题的进展>
    阻塞点: <该话题的阻塞问题点>
    下一步计划: <该话题的下一步计划>
    
    聊天记录: <{text}>
    
    """

prompt_template = ChatPromptTemplate.from_template(template_string)


logger = logging.getLogger(__name__)
#消息处理加工，prompt工程，处理单个消息和多个消息

sql_query = "SELECT product_name FROM Product WHERE product_price > 100"


lessmessage = 200
#limit = 1800
limit = 4000
countlimit = 5


def summarize_text(input: str) -> str:
    #print(input)
    customer_messages = prompt_template.format_messages(text=input)
    print(customer_messages)
    summary = chat(customer_messages)
    print(summary.content)
    return summary.content


def split_messages(messages: List[str]) -> List[str]:
    chunks = []
    current_chunk = ''
    for message in messages:
        if len(current_chunk) + len(message) + 2 > limit:
            chunks.append(current_chunk.strip())
            current_chunk = ''
        current_chunk += message + '\n\n'
    if current_chunk:
        chunks.append(current_chunk.strip())
    if not chunks:
        raise ValueError("Some messages are longer than the limit.")
    return chunks
    
def get_message_list(messages):
    message_strings = []
    for msg in messages:
        content = msg['eventData']['notify']
        message_strings.append(content)
    return message_strings

def summary(messages: List[str]) -> List[str]:
    # 合并成一个字符串
    message_list = get_message_list(messages)
    
    if len(message_list) < countlimit:
        return "聊天记录太少，不需要总结"

    text = "\n\n".join(message_list)
    result = ''

    if len(text) <= lessmessage:
        result = "聊天记录太少，不需要总结"
        
    elif len(text) <= limit:
        result = summarize_text(text)
        if result == "服务出错":
            return "服务出错"
        
    else:
        # 分割信息并处理
        chunks = split_messages(message_list)
        summaries = []
        for chunk in chunks:
            print(f"chunk字符串的长度为：{len(chunk)}")
            print(len(chunks))
            summaries.append(summarize_text(chunk))
        for summary in summaries:
            if summary == "服务出错":
                return "服务出错"
        result = '当日聊天信息太长，分批进行摘要总结，以"&&"进行分割:\n\n' + '\n\n&&\n\n'.join(summaries)
        #result = finalsum(summaries)
        
    #print('总结结果：\n' + result) 
    logger.info(f'总结结果: {result}')
    return result


summarize_text('今天我第一天上班')
